<?php
/**
 * 公开接口API
 * 家乡会等接口
 * 不需要验证用户身份token
 * @author David
 *
 */
namespace Api\Controller;

use Common\Controller\ApiController;
use Think\Page;
use Api\Common\Common;

class CenterController extends ApiController{
    
    //我个个人中心主页
    public function index()
    {
        $uid=$this->member_info['member_id'] ? $this->member_info['member_id'] : 0;
        $detail=$this->comMod->getMemberInfoByID($uid,$this->select_fields_column['member']);
        $user_token=$this->comMod->table(C('DB_PREFIX').'mb_user_token')->where(array('member_id'=>$this->member_info['member_id']))->find();
        $detail=$this->filter_member_info($detail,$user_token['token']);
        // $detail['signature']=$detail['signature'] ? $detail['signature'] : '';
        $cond=array('reply_uid'=>$this->member_info['member_id']); 
        $count1 = $this->comMod->table(C('DB_PREFIX').'app_comment')->where($cond)->count();
        $count2 = $this->comMod->table(C('DB_PREFIX').'app_vote')->where($cond)->count();
        $count3 = $this->comMod->table(C('DB_PREFIX').'app_zan')->where($cond)->count();
        $count4 = $this->comMod->table(C('DB_PREFIX').'app_system_msg')->where($cond)->count();
        $detail['msg_count']=$count1+$count2+$count3+$count4;

        $this->myApiPrint(200,$detail);
    }

    //我的动态
    public function getMyDynamics()
    {
        $table='sectiontopic';
        $cond=array('member_id'=>$this->member_info['member_id']);
        $cond['article_show']=1;
        $page=$this->comMod->initPage($table,$cond,$this->pageNum);
        $totalPages = ceil($page->totalRows / $page->listRows); 
        $extend_data = $this->mobile_page($totalPages);
        $list=$this->comMod->getList($table,$cond,'*','article_id desc',$page->firstRow,$page->listRows);
        foreach($list as $key=>$value){
            $value2=$this->comMod->bangdanHandle($value);
            $list[$key]=$value2;
        }
        $this->myApiPrint(200,$list,$extend_data);
    }

    //我的收藏
    public function getMyCollect()
    {
        //获取收藏帖子id
        $collect_aid_list=$this->comMod->getList('app_zan',array('uid'=>$this->member_info['member_id']),'aid','');
        $aid_arr=array();
        foreach ($collect_aid_list as $key => $value) {
            $aid_arr[]=$value['aid'];
        }
        $aid_in=implode(',', $aid_arr);

        //获取列表数据
        
        if(!empty($aid_in)){
            $table='sectiontopic';
            $cond['article_show']=1;
            $cond['article_id']=array('in',$aid_in);  
            $page=$this->comMod->initPage($table,$cond,$this->pageNum);
            $totalPages = ceil($page->totalRows / $page->listRows); 
            $extend_data = $this->mobile_page($totalPages);
            $list=$this->comMod->getList($table,$cond,'*','article_id desc',$page->firstRow,$page->listRows);
            foreach($list as $key=>$value){
                $value2=$this->comMod->bangdanHandle($value);
                $list[$key]=$value2;
            }
        }else{
            $list='';
            $extend_data = $this->mobile_page(0);
        }
        
        $this->myApiPrint(200,$list,$extend_data);
    }

    //逻辑删除的动态
    public function deleteMyDynamics()
    {
        $uid=$this->member_info['member_id'] ? $this->member_info['member_id'] : 0;
        $condition['article_id']=$_REQUEST['tid'];
        $condition['member_id']=$uid;
        $condition['article_show']=1;
        $topic=$this->comMod->detail('sectiontopic',$condition,'member_id');
        if(empty($topic['member_id']) || (isset($topic['member_id']) && $topic['member_id']!=$uid)){
            $this->myApiPrint(-3,'',array('msg'=>'该文章不存在或没有权限操作'));
        }
        $result=$this->comMod->saveData('sectiontopic',$condition,array('article_show'=>0));  //逻辑删除
        if($result){
            $this->myApiPrint(200);
        }else{
            $this->myApiPrint(-3);
        }
    }

    //我的消息（评论消息，推荐票消息，赞消息，系统消息）
    public function getMyMessage()
    {   
        $order='id desc'; 
        $table='comment';
        
        switch ($_REQUEST['type']) {
            case 'comment':
                $table='app_comment';

                break;
            case 'vote':
                $table='app_vote';
                
                break;
            case 'zan':
                $table='app_zan';

                break;
            case 'system':
                $table='app_system_msg';  //我的消息默认界面调用

                break;
            default:
                // $table='app_system_msg';
                $this->myApiPrint(401); //不存在该消息类型
                break;
        }

        //消息进入默认页面
        $cond_count=array('reply_uid'=>$this->member_info['member_id'],'is_read'=>0); 
        $count1 = $this->comMod->table(C('DB_PREFIX').'app_comment')->where($cond_count)->count();
        $count2 = $this->comMod->table(C('DB_PREFIX').'app_vote')->where($cond_count)->count();
        $count3 = $this->comMod->table(C('DB_PREFIX').'app_zan')->where($cond_count)->count();

        if($_REQUEST['type']!='system'){
            $condition=array('reply_uid'=>$this->member_info['member_id'],'is_read'=>0); //被回复者id
            // $this->myApiPrint(-3,'',array('msg'=>$this->member_info['member_id'].'--'));
            $page=$this->comMod->initPage($table,$condition,$this->pageNum);
            $totalPages = ceil($page->totalRows / $page->listRows); 
            $extend_data = $this->mobile_page($totalPages);
            $list=$this->comMod->getList($table,$condition,'*',$order,$page->firstRow,$page->listRows);
            //处理数据
            foreach ($list as $key => $value) {
                $from_user=$this->comMod->getMemberInfoByID($value['uid'],'avatar,truename,member_id,member_name');
                $from_user['avatar']=$from_user['avatar'] ? PicPath.$from_user['avatar'] : DEFAULT_CIRCLE_AVATAR;
                $from_user['member_name']=$from_user['truename'] ? $from_user['truename'] : '';
                unset($from_user['truename']);
                // $topic=$this->comMod->detail('sectiontopic',array('article_id'=>$value['aid']));
                $topic=$this->comMod->detail('sectiontopic',array('article_id'=>$value['aid']),'article_id,article_title,article_desc,article_pic,ac_id');
                $topic=$this->comMod->MyMessageHandle($topic);
                $list[$key]['from_user']=$from_user;
                $list[$key]['topic']=$topic;
                if(!isset($list[$key]['content'])) $list[$key]['content']='已投票';
                $unread_cid[]=$value['id'];
                
            }
            
            //更新非系统消息为已读状态
            if(!empty($unread_cid)){
                $unread_cid_in=implode(',', $unread_cid);
                $where_update_status['id']=array('in',$unread_cid_in);
                $this->comMod->saveData($table,$where_update_status,array('is_read'=>1));
            }

        }else{

            $order='add_time desc'; 
            $condition=array('reply_uid'=>$this->member_info['member_id']);
            $page=$this->comMod->initPage($table,array(),$this->pageNum);
            $totalPages = ceil($page->totalRows / $page->listRows); 
            $extend_data = $this->mobile_page($totalPages);

            // $cond['msg_id'] = array('exp','is null');
            // $cond='msg_id is null or (is_read=0 and reply_uid='.$this->member_info['member_id'].')';
            $cond='msg_id is null or reply_uid='.$this->member_info['member_id'];

            $total_count = M('app_system_msg_text')->alias('e')->join('LEFT JOIN mxd_app_system_msg as m'.' ON e.id = m.msg_id' )->field('e.title,e.content,e.add_time,m.*')->where($cond)->count();
            $page = new Page($total_count,50);

            $list=M('app_system_msg_text')->alias('e')->join('LEFT JOIN mxd_app_system_msg as m'.' ON e.id = m.msg_id' )->field('e.title,e.content,e.add_time,m.*')->where($cond)->limit($page->firstRow,$page->listRows)->order($order)->select();
            // print_r($list);
        }

        $extend_data['comment_num']=$count1;
        $extend_data['vote_num']=$count2;
        $extend_data['zan_num']=$count3;

        
        $this->myApiPrint(200,$list,$extend_data);
    }

    //系统消息查看更新状态
    public function readMessage()
    {
        $where['reply_uid']=$this->member_info['member_id'];
        $where['msg_id']=$_REQUEST['msg_id'];
        $message=$this->comMod->detail('app_system_msg',$where,'id');
        if(empty($message)){
            $data['is_read']=1;
            $data['msg_id']=$_REQUEST['msg_id'];
            $data['uid']=0;
            $data['reply_uid']=$_REQUEST['msg_id'];
            $this->comMod->addData('app_system_msg',$data);
        }else{
            $this->comMod->saveData('app_system_msg',$where,array('is_read'=>1));
        }
        $data=$this->comMod->detail('app_system_msg_text',array('id'=>$_REQUEST['msg_id']),'*');
        // $data['title']='系统消息';
        $this->myApiPrint('',$data);
    }

    //乾坤币明细列表
    public function getCoinLog()
    {
        $table='coin_log';
        $cond=array('uid'=>$this->member_info['member_id']);
        $page=$this->comMod->initPage($table,$cond,$this->pageNum);
        $totalPages = ceil($page->totalRows / $page->listRows); 
        $extend_data = $this->mobile_page($totalPages);
        $list=$this->comMod->getList($table,$cond,'*','id desc',$page->firstRow,$page->listRows);
        $list=$this->comMod->CoinHandle($list);
        $this->myApiPrint(200,$list,$extend_data);
    }

    //积分明细列表
    public function getPointLog()
    {
        $table='point_log';
        $cond=array('uid'=>$this->member_info['member_id']);
        $page=$this->comMod->initPage($table,$cond,$this->pageNum);
        $totalPages = ceil($page->totalRows / $page->listRows); 
        $extend_data = $this->mobile_page($totalPages);
        $list=$this->comMod->getList($table,$cond,'*','id desc',$page->firstRow,$page->listRows);
        $list=$this->comMod->CoinHandle($list);
        $this->myApiPrint(200,$list,$extend_data);
    }

    //任务列表完成情况
    public function getSignTask()
    {
        $today_start=strtotime(date('Y-m-d'));    //今天早上凌晨0点
        $cond=array('uid'=>$this->member_info['member_id']);
        $page=$this->comMod->initPage('sign_task',array(),$this->pageNum);
        $totalPages = ceil($page->totalRows / $page->listRows);
        $extend_data = $this->mobile_page($totalPages);
        $list=$this->comMod->getList('sign_task',array(),'*','id desc',$page->firstRow,$page->listRows);
        foreach ($list as $key => $value) {
            $cond['task_id']=$value['id'];
            $cond['finish_time']=array('gt',$today_start); //过滤当天的数据
            $sign_task_finished_detail=$this->comMod->detail('sign_task_finished',$cond,'*');
            $task_finish_time=date('Y-m-d', $sign_latest[0]['sign_time']);
            $list[$key]['is_finish']=$value['content2'];
        }
        $this->myApiPrint(200,$list,$extend_data);
    }

    // //任务列表完成情况
    // public function getSignTask()
    // {
    //     $today_start=strtotime(date('Y-m-d'));    //今天早上凌晨0点
    //     $cond=array('uid'=>$this->member_info['member_id']);
    //     $list=$this->comMod->getList('sign_task',array(),'*','id desc');
    //     foreach ($list as $key => $value) {
    //         $cond['task_id']=$value['id'];
    //         $cond['finish_time']=array('gt',$today_start); //过滤当天的数据
    //         $sign_task_finished_detail=$this->comMod->detail('sign_task_finished',$cond,'*');
    //         $task_finish_time=date('Y-m-d', $sign_latest[0]['sign_time']);
    //         $list[$key]['is_finish']=$sign_task_finished_detail ? '已完成' : '未完成';
    //     }
    //     $this->myApiPrint(200,$list);
    // }

    //签到
    public function addSign()
    {   
        $coin_rule=C('COIN_RULE');
        $add_coin_amount=$coin_rule['signed'];
        $cond=array('uid'=>$this->member_info['member_id']);
        $sign_latest=$this->comMod->table(C('DB_PREFIX').'signed')->where($cond)->order('id desc')->limit(0,1)->select();
        $sign_time=date('Y-m-d', $sign_latest[0]['sign_time']);
        $today=date('Y-m-d', NOW_TIME);
        //每天只能签到一次
        if($today==$sign_time){
            $this->myApiPrint(4009); 
        }
        $data['uid']=$this->member_info['member_id'];
        $data['sign_time']=NOW_TIME;
        $data['task_id']=1;
        $res=$this->comMod->addData('signed',$data);
        if($res){

            //更新用户最近签到时间
            $this->comMod->saveData('member',array('member_id'=>$this->member_info['member_id']),array('latest_signed_time'=>$today));
            
            $log_data['member_id']=$this->member_info['member_id'];
            $log_data['member_name']=$this->member_info['member_name'];
            //添加乾坤币记录
            $this->comMod->addCoinLog('coin_log',$log_data,'signed');
            //连续5天签到
            // $signed_detail=$this->comMod->detail('signed',array('id'=>$res),'*');
            // $day_1=strtotime("-5 day",NOW_TIME);
            // $cond=array('uid'=>$this->member_info['member_id']);
            // $cond['sign_time']=array('between',$day_1.','.NOW_TIME);
            // $list=$this->comMod->getList('signed',$cond,'*','sign_time desc',0,5);
            // foreach ($list as $key => $value) {
            //     $list[$key]=date('Y-m-d', $value['sign_time']);
            // }
            // $serial_days=Common::continue_days($list);
            // if($serial_days==5){
            //     $add_coin_amount+=$coin_rule['serial_signed'];
            //     //添加乾坤币记录
            //     $this->comMod->addCoinLog('coin_log',$log_data,'serial_signed');
            //     //插入连续签到完成任务记录
            //     // $this->comMod->addSignFinishRecord($this->member_info['member_id'],1);

            // }
            //更新个人金币数量
            $cond=array();
            $cond['member_id']=$this->member_info['member_id'];
            $this->comMod->selfUpdateField('member','coin',$cond,$operate="+",$add_coin_amount);

            // if($serial_days==5){
            //     $this->myApiPrint(202);
            // }else{
                //插入每日签到任务记录
                $this->comMod->addSignFinishRecord($this->member_info['member_id'],46);
                $this->myApiPrint(200,'',array('msg'=>'签到成功'));
            // }

        }else{
            $this->myApiPrint(-3);
        }
    }

	//用户信息(自己和他人)暂时app端未调用
    public function getUserInfo()
    {   
        $uid=$this->member_info['member_id'] ? $this->member_info['member_id'] : 0;
        $member_info=$this->comMod->getMemberInfoByID($uid,$this->select_fields_column['member']);
        $member_info['truename']=$member_info['truename'] ? $member_info['truename'] : '';
        $member_info['birthday']=$member_info['birthday'] ? $member_info['birthday'] : '';
        $member_info['country']=$member_info['country'] ? $member_info['country'] : '';
        if($member_info['gender']){
            $member_info['gender']=$member_info['gender']==1 ? '男' : '女'; //1-男，2-女
        }else{
            $member_info['gender']='保密'; //0-保密
        }
        $member_info['avatar']=$member_info['avatar'] ? PicPath.$member_info['avatar'] : DEFAULT_CIRCLE_AVATAR;
        $school_info=$this->getSchoolDada(unserialize($member_info['school']));
        $result=array_merge($member_info,$school_info);
        unset($result['school']);
        $this->myApiPrint('',$result);
    }

    //修改用户个人信息（登录验证）
    public function updateUserInfo() {

        $member_info=$this->comMod->getMemberInfoByID($this->member_info['member_id'],'school');
        $school_info=unserialize($member_info['school']);
        extract($school_info);
        unset($school_info);
        $result['name']=$name ? $name : '';
        $result['school_id']=$school_id ? $school_id : '';
        $result['depart']=$depart ? $depart : '';
        $result['start_year']=$start_year ? $start_year : '';
        $result['class']=$class ? $class : '';
        $result['room']=$room ? $room : '';
        $result['middle_school']=$middle_school ? $middle_school : '';
        $result['education']=$education ? $education : '';

         //修改头像
         if($_FILES['avatar']['size'])
         {
            $arc_img = 'avatar_'.$this->member_info['member_id'];
            $param = array('savePath'=>'member/avatar/','subName'=>'','files'=>$_FILES['avatar'],'saveName'=>$arc_img,'saveExt'=>'');
            $up_return = upload_one($param);
            if($up_return == 'error'){
                $this->myApiPrint(4005);
            }else{
                $data['avatar'] = $up_return;
                // $this->myApiPrint(200,'',array('msg'=>$this->member_info['member_id'].'---'.$_REQUEST['key']));
            }
         }

         if($_REQUEST['truename']){
            $data['truename']=$_REQUEST['truename'];
         }
         if($_REQUEST['signature']){
            $data['signature']=$_REQUEST['signature'];
         }
         if($_REQUEST['birthday']){
            $data['birthday']=$_REQUEST['birthday'];
         }
         if( (isset($_REQUEST['gender']) && empty($_REQUEST['gender'])) || intval($_REQUEST['gender'])>0 ){
            $data['gender']=$_REQUEST['gender'];
            // $this->myApiPrint(200,'',array('msg'=>$_REQUEST['gender']));
         }
         if($_REQUEST['province']){
            $data['province']=$_REQUEST['province'];
         }
         if($_REQUEST['city']){
            $data['city']=$_REQUEST['city'];
         }
         if($_REQUEST['school_id']){
            $school=$this->comMod->detail('school_class',array('id'=>$_REQUEST['school_id']),'id,ac_name');
            $result['school_id']=$_REQUEST['school_id'];
            $result['name']=$school['ac_name'];
            $data['school']=serialize($result);
         }
         if($_REQUEST['depart']){
            $result['depart']=$_REQUEST['depart'];
            $data['school']=serialize($result);
         }
         if($_REQUEST['start_year']){
            $result['start_year']=$_REQUEST['start_year'];
            $data['school']=serialize($result);
         }
         if($_REQUEST['class']){
            $result['class']=$_REQUEST['class'];
            $data['school']=serialize($result);
         }
         if($_REQUEST['room']){
            $result['room']=$_REQUEST['room'];
            $data['school']=serialize($result);
         }
         if($_REQUEST['middle_school']){
            $result['middle_school']=$_REQUEST['middle_school'];
            $data['school']=serialize($result);
         }
         if($_REQUEST['education']){
            $result['education']=$_REQUEST['education'];
            $data['school']=serialize($result);
         }
        $where=array('member_id'=>$this->member_info['member_id']);
        try {
            $result=$this->comMod->saveData('member',$where,$data);
            $this->myApiPrint(200);
        } catch (Exception $e) {
            $this->myApiPrint(-3);
        }
        
    }

    //学校，院系选择列表
    public function getSchoolList()
    {
        //搜索学校，院系
        if(intval($_REQUEST['name'])){
            $condition['ac_name']=array('like','%'.$_REQUEST['name'].'%');
        }
        $pid=intval($_REQUEST['sch_pid']);
        $count = $this->comMod->table(C('DB_PREFIX')."school_class")->where(array('ac_parent_id'=>$pid))->count();
        $page = new Page($count,$this->pageNum);
        $totalPages = ceil($page->totalRows / $page->listRows); //总页数
        $extend_data= $this->mobile_page($totalPages);

        $list=$this->comMod->getList('school_class',array('ac_parent_id'=>$pid),'*','id asc',$page->firstRow,$page->listRows);
        
        $this->myApiPrint('',$list,$extend_data);
    }

    //兑换商品列表
    public function exchange_goods_list()
    {
        $table='exchange_goods';
        $cond=array('status'=>1);
        $page=$this->comMod->initPage($table,$cond,$this->pageNum);
        $totalPages = ceil($page->totalRows / $page->listRows); 
        $extend_data = $this->mobile_page($totalPages);
        $list=$this->comMod->getList($table,$cond,'*','id desc',$page->firstRow,$page->listRows);
        foreach ($list as $key => $value) {
            $list[$key]['logo']=$value['logo'] ? $value['logo'] : '';
            $list[$key]['score']=$value['score'].'乾坤币';
        }
        $this->myApiPrint(200,$list,$extend_data);
    }

    //乾坤币兑换操作(已经计算了乾坤币)
    public function exchange_done(){

        $uid=$this->member_info['member_id'] ? $this->member_info['member_id'] : 0;
        $goods_id=$_REQUEST['goods_id'];
        $exist_tools=$this->comMod->detail('member_tools',array('member_id'=>$this->member_info['member_id'],'goods_id'=>$goods_id));
        $good_detail=$this->comMod->detail('exchange_goods',array('id'=>$goods_id)); //商品详情

        //判断乾坤币是否足够
        if($this->member_info['coin']>=$good_detail['score']){

            //----每天可消费乾坤币逻辑start
            $today=date('Y-m-d');
            $member_level_info=getMemberLevel($this->member_info['point']);//每天可用乾坤币限制
            $memberInfo=$this->comMod->detail('member',array('member_id'=>$uid),'exchange_info');
            $update_exchange_data=array();
            if($memberInfo['exchange_info']!=null && !empty($memberInfo['exchange_info'])){

                $exchange_info=unserialize($memberInfo['exchange_info']);

                if($exchange_info['date']!=$today){
                    $update_exchange_data['date']=$today;
                    $update_exchange_data['count']=$good_detail['score'];
                }else{
                    $update_exchange_data['count']=$exchange_info['count']+$good_detail['score'];
                    $update_exchange_data['date']=$exchange_info['date'];
                }
                // if($exchange_info['count']+$good_detail['score']>400){
                if($update_exchange_data['count']>$member_level_info['coin_exchange_num_limit']){
                    
                    $this->myApiPrint(-3,'',array('msg'=>'超过了每天兑换额度，明天继续哦'));
                }

            }else{
                $update_exchange_data['count']=$good_detail['score'];
                $update_exchange_data['date']=$today;
            }
            //----每天可消费乾坤币逻辑end

            if(empty($exist_tools)){
                $data['member_id']=$this->member_info['member_id'];
                $data['goods_id']=$goods_id;
                $data['name']=$good_detail['name'];
                $data['logo']=$good_detail['logo'] ? $good_detail['logo'] : '';
                $data['amount']=1;
                $result=$this->comMod->addData('member_tools',$data);
            }else{
                $this->comMod->selfUpdateField('member_tools','amount',array('goods_id'=>$goods_id,'member_id'=>$this->member_info['member_id']),$operate="+",1);
            }
            //更新个人乾坤币数量和兑换每天乾坤币消费数
            $exchange_info_serial=serialize($update_exchange_data);
            $member_data_save['exchange_info']=$exchange_info_serial;
            $member_data_save['coin']=array('exp','coin-'.$good_detail['score']);
            $this->comMod->saveData('member',array('member_id'=>$uid),$member_data_save);

        }else{
            $this->myApiPrint(-3,'',array('msg'=>'乾坤币不够'));
        }

        $this->myApiPrint(203); //兑换成功msg
        
    }

    //我的道具
    public function my_tools()
    {
        $table='member_tools';
        $cond=array('member_id'=>$this->member_info['member_id']);
        $page=$this->comMod->initPage($table,$cond,$this->pageNum);
        $totalPages = ceil($page->totalRows / $page->listRows); 
        $extend_data = $this->mobile_page($totalPages);
        $list=$this->comMod->getList($table,$cond,'*','id desc',$page->firstRow,$page->listRows);

        // foreach ($list as $key => $value) {
        //     $value['name']=$member_level_info['level'];
        //     $list[$key]=$value;
            
        // }
        $this->myApiPrint(200,$list,$extend_data);
    }

    //退出登录
    public function Logout(){

        if($this->member_info['member_id'] == $_REQUEST['uid']) {
            $condition = array();
            $condition['member_id'] = $this->member_info['member_id'];
            $condition['client_type'] = $_REQUEST['client'];
            $this->tokenMod->delMbUserToken($condition);
            $this->myApiPrint(200);
        } else {
            $this->myApiPrint(-3);
        }
    }

    //登录
    public function Login()
    {
        $condition=array('pwd'=>re_md5(trim($_REQUEST['pwd'])));
        // if(!empty($_REQUEST['client'])){
        //     $condition['mobile'] = $_REQUEST['mobile'];
        // }else{
        //     $condition['email'] = $_REQUEST['email'];
        // }

        // if(preg_match("/1[34578]{1}\d{9}$/",$_REQUEST['member_name'])){
        //     $condition['mobile'] = $_REQUEST['member_name']; //手机号码登录
        // }else{
            $condition['member_name'] = $_REQUEST['member_name']; //用户名登录
        // }

        // $member_info = M('member')->where($condition)->find(); 
            $member_info=M('member')->field($this->select_fields_column['member'])->where($condition)->find();

        //判断用户是否存在
        if (!$member_info) {
            $this->myApiPrint(-1);
        }else{
//            $ip = get_client_ip();
//            $Ip = new \Org\Net\IpLocation();
//            $area = $Ip->getlocation($ip);
//            $ins_data ['last_login_time'] = date('Y-m-d H:i:s', NOW_TIME);
//            $ins_data ['last_login_ip'] = $ip;
//            $ins_data ['last_location'] = $area ['country'] . $area ['area'];

            //重新登陆后以前的令牌失效
            $condition = array();
            $condition['member_id'] = $member_info['member_id'];
            $condition['client_type'] = $_REQUEST['client'];
            $this->tokenMod->delMbUserToken($condition);
            //会员登录（重新生成token）
            $token = $this->_get_token($member_info['member_id'], $member_info['member_name'], $_REQUEST['client']);
            if($token) {
                // $this->myApiPrint('',array('member_id' => $member_info['member_id'],'member_name' => $member_info['member_name'], 'key' => $token));
                $this->member_info=$this->filter_member_info($member_info,$token);
                $this->myApiPrint('',$this->member_info);
            }else {
                //令牌失效---code=-1
                $this->myApiPrint('-2');
            }
        }
    }

    //注册
    public function Register()
    {

//        if(!empty($_REQUEST['client'])){
//            $condition['mobile'] = $_REQUEST['mobile'];
//        }else{
//            $condition['email'] = $_REQUEST['email'];
//        }

        $condition['member_name'] = $_REQUEST['member_name'];
        $condition['pwd'] = re_md5(trim($_REQUEST['pwd']));
        $member_info = M('member')->where($condition)->find(); //判断用户时候存在
        if (!empty($member_info)) {
            $this->myApiPrint(4003);
        }else {
            //注册
            $condition['avatar'] =  C('DEFAULT_USER_IMG_PATH');
            $condition['register_time'] = NOW_TIME;
            // $condition['client'] = $_REQUEST['client'];
            
            $school['name']= $_REQUEST['school_name'];
            $school['school_id']=$_REQUEST['school_id'];
            $school['depart']=$_REQUEST['depart'];
            $school['start_year']=$_REQUEST['start_year'];
            $school['education']=$_REQUEST['education'];
            $school['class']='';
            $school['room']='';
            $school['middle_school']='';
            $condition['school']=serialize($school);

            $member_id = M('member')->add($condition);
            if ($member_id > 0) {
                $token = $this->_get_token($member_id, $condition['member_name'], $_REQUEST['client']);
                if($token) {
                    // $this->myApiPrint(100,array('member_id'=>$member_id,'member_name' => $condition['member_name'], 'key' => $token));
                    $member_info=M('member')->field($this->select_fields_column['member'])->where(array('member_id'=>$member_id))->find();
                    $this->member_info=$this->filter_member_info($member_info,$token);
                    unset($school);
                $this->myApiPrint('',$this->member_info);
                } else {
                    $this->myApiPrint(4004);
                }
            } else {
                $this->myApiPrint(4004);
            }
        }
    }




    ////==========================================================================
        //登录
    public function Login2()
    {
        $condition=array('pwd'=>re_md5(trim($_REQUEST['pwd'])));
        // if(!empty($_REQUEST['client'])){
        //     $condition['mobile'] = $_REQUEST['mobile'];
        // }else{
        //     $condition['email'] = $_REQUEST['email'];
        // }

        // if(preg_match("/1[34578]{1}\d{9}$/",$_REQUEST['member_name'])){
        //     $condition['mobile'] = $_REQUEST['member_name']; //手机号码登录
        // }else{
            $condition['member_name'] = $_REQUEST['member_name']; //用户名登录
        // }

        // $member_info = M('member')->where($condition)->find(); 
            $member_info=M('member')->field($this->select_fields_column['member'])->where($condition)->find();

        //判断用户是否存在
        if (!$member_info) {
            $this->myApiPrint(-1);
        }else{

            //重新登陆后以前的令牌失效
            $condition = array();
            $condition['member_id'] = $member_info['member_id'];
            $condition['client_type'] = $_REQUEST['client'];
            $this->tokenMod->delMbUserToken($condition);
            //会员登录（重新生成token）
            $token = $this->_get_token($member_info['member_id'], $member_info['member_name'], $_REQUEST['client']);
            if($token) {
                $this->member_info=$this->filter_member_info($member_info,$token);
                $this->myApiPrint('',$this->member_info);
            }else {
                //令牌失效---code=-1
                $this->myApiPrint('-2');
            }
        }
    }

    //注册
    public function Register2()
    {

        $condition['member_name'] = $_REQUEST['member_name'];
        $condition['pwd'] = re_md5(trim($_REQUEST['pwd']));
        $condition['hx_id'] = Common::setHuanxinId();  //生成环信ID
        $member_info = M('member')->where($condition)->find(); //判断用户时候存在
        if (!empty($member_info)) {
            $this->myApiPrint(4003);
        }else {
            //注册
            $condition['truename'] = $_REQUEST['member_name'];
            $condition['nickname'] = $_REQUEST['member_name'];
            $condition['avatar'] =  C('DEFAULT_USER_IMG_PATH');
            $condition['register_time'] = NOW_TIME;
            
            $school['name']= $_REQUEST['school_name'];
            $school['school_id']=$_REQUEST['school_id'];
            $school['depart']=$_REQUEST['depart'];
            $school['start_year']=$_REQUEST['start_year'];
            $school['education']=$_REQUEST['education'];
            $school['class']='';
            $school['room']='';
            $school['middle_school']='';
            $condition['school']=serialize($school);
            unset($school);

            //添加用户
            $member_id = M('member')->add($condition);

            if ($member_id > 0) {
                
                $token = $this->_get_token($member_id, $condition['member_name'], $_REQUEST['client']);

                if($token) {

                    //获取完整用户信息
                    $member_info=$this->comMod->detail('member',array('member_id'=>$member_id),$this->select_fields_column['member']);
                    $this->member_info=$this->filter_member_info($member_info,$token);
                    
                    //更新头像和第三方登录id
                    $member_save_data=array();
                    // if($_FILES['avatar']['size'])
                    // {
                    //     $arc_img = 'avatar_'.$member_id;
                    //     $param = array('savePath'=>'member/avatar/','subName'=>'','files'=>$_FILES['avatar'],'saveName'=>$arc_img,'saveExt'=>'');
                    //     $up_return = upload_one($param);
                    //     if($up_return == 'error'){
                    //         $this->myApiPrint('',$this->member_info);
                    //     }else{
                    //         $member_save_data['avatar'] = $up_return;
                    //     }
                    // }
                    // $this->myApiPrint(4003,'',array('msg'=>$member_id.'---'.$_REQUEST['third_login_id'].'---'.$this->getThirdPlatformClumn()));
                    $query_column=$this->getThirdPlatformClumn();
                    $third_login_id = isset($_REQUEST['third_login_id']) ? trim($_REQUEST['third_login_id']) : '';
                    if($third_login_id==''){
                        $this->myApiPrint(4004);
                    }
                    $member_save_data[$query_column]=$third_login_id;
                    $this->comMod->saveData('member',array('member_id'=>$member_id),$member_save_data);


                    $this->myApiPrint('',$this->member_info);

                } else {
                    $this->myApiPrint(4004);
                }
            } else {
                $this->myApiPrint(4004);
            }
        }
    }

    //判断用户是否绑定了第三方登录（新浪微博-sina，腾讯QQ-qq，微信-weixin绑定）
    public function check_third_bind()
    {
        $third_login_id = isset($_REQUEST['third_login_id']) ? trim($_REQUEST['third_login_id']) : '';
        $third_type = isset($_REQUEST['third_type']) ? trim($_REQUEST['third_type']) : '';
        $query_column='';
        if(!empty($third_login_id)){
            
            switch ($third_type) {
                case 'sina':
                    $query_column='sina_login_id';
                    break;
                case 'qq':
                    $query_column='qq_login_id';
                    break;
                case 'weixin':
                    $query_column='weixin_login_id';
                    break;                                    
            }

            $condition[$query_column]=$third_login_id;
            $member_info=$this->comMod->detail('member',$condition,$this->select_fields_column['member']);
            
            if(!empty($member_info)){
                $token = $this->_get_token($member_info['member_id'], $member_info['member_name'], $_REQUEST['client']);
                $extend_data=array();
                if($token) {

                    $this->member_info=$this->filter_member_info($member_info,$token);
                    $this->myApiPrint(200,$this->member_info,array('msg'=>'第三方登录成功'));

                } else {
                    $this->myApiPrint(-2,'',array('msg'=>'帐号异常登录')); 
                }
            }else{
                $this->myApiPrint(-6,'',array('msg'=>'帐号未绑定第三方登录')); //跳到注册页面
            }
        }else{
            $this->myApiPrint(-7,'',array('msg'=>'第三方登录ID过期')); 
        }
    }

    //第三方解除绑定
    public function unbind()
    {
        $query_column='';
        $uid=$this->member_info['member_id'] ? $this->member_info['member_id'] : 0;
        $third_type = isset($_REQUEST['third_type']) ? trim($_REQUEST['third_type']) : '';
        switch ($third_type) {
            case 'sina':
                $query_column='sina_login_id';
                break;
            case 'qq':
                $query_column='qq_login_id';
                break;
            case 'weixin':
                $query_column='weixin_login_id';
                break;                                    
        }
        //解绑定
        $cond['uid']=$uid;
        $data[$query_column]=''; 
        $result=$this->comMod->saveData('member',$cond,$data);
        // $result=M('member')->where($cond)->delete();
        try {
            echo '解除绑定成功';
        } catch (Exception $e) {
            echo '解除绑定失败';
        }
        

    }

    

    public function getThirdPlatformClumn()
    {
        $query_column='';
        $third_type = isset($_REQUEST['third_type']) ? trim($_REQUEST['third_type']) : '';
        
        switch ($third_type) {
            case 'sina':
                $query_column='sina_login_id';
                break;
            case 'qq':
                $query_column='qq_login_id';
                break;
            case 'weixin':
                $query_column='weixin_login_id';
                break;                                    
        }

        return $query_column;
    }    


}